//
//  EditMyFamilyDetialViewController.m
//  安好
//
//  Created by lianchuang on 14-12-1.
//  Copyright (c) 2014年 lianchuangbrother. All rights reserved.
//
#import <AssetsLibrary/AssetsLibrary.h>
#import "MainViewController.h"
#import "EditMyFamilyDetialViewController.h"
//编辑家人头像
#import "FamilyInfoFirstSectionCell.h"
//具体cell
#import "AddFamilyRemindCell.h"

#import "AFNetworking.h"
//push到书写昵称和姓名的页面
#import "WriteFamilyViewController.h"
//对电话号码判断
#import "CheckNumberClass.h"
//关系picker
#import "FamilyRelationshipPickerView.h"
//日期picker
#import "MyDatePickerView.h"
//提示
#import "MBProgressHUD.h"
//对电话号码的判断合法
#import "CheckNumberClass.h"

//从用药提醒过来的话--删除家人之后回到用药提醒家人列表页面
#import "TakeDrugsViewController.h"
//从我的家人 过来的话--删除家人之后回到我的家人
#import "MyFamilyViewController.h"

#define IPhone6Plus ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)

#define cellLineColor [UIColor colorWithRed:221/255.0 green:221/255.0 blue:221/255.0 alpha:1];
@interface EditMyFamilyDetialViewController ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDataSource,UIPickerViewDelegate,WriteFamilyViewControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,MBProgressHUDDelegate,UIActionSheetDelegate>

@property(nonatomic,strong)UITableView * tableView;
/**
 * 家人的所有参数
 */
@property(nonatomic,strong)NSMutableDictionary * familyParameters;
/**
 *  这个字典帮助找到key
 */
@property(nonatomic,strong)NSDictionary * tempDic;
/**
 *  push到write页面的提示
 */
@property(nonatomic,strong)NSDictionary * placeholedeDic;
/**
 *  必填提示
 */
@property(nonatomic,strong)NSArray * requiredRemiderArray;
/**
 *  必填内容
 */
@property(nonatomic,strong)NSArray * requiredValueArray;
/**
 *  第三段--选填提示
 */
@property(nonatomic,strong)NSArray * optionRemindFirstArray;
/**
 * 第三段--选填内容
 */
@property(nonatomic,strong)NSArray * optionValueFirstArray;
/**
 *  第四段--选填提示
 */
@property(nonatomic,strong)NSArray * optionReminderSecondArray;
/**
 *  第四段--选填内容
 */
@property(nonatomic,strong)NSArray * optionValueSecondArray;
/**
 *  关系选择器
 */
@property(nonatomic,strong)FamilyRelationshipPickerView *relationShipView;
/**
 *  日期选择器
 */
@property(nonatomic,strong)MyDatePickerView * myDatePickerView;
/**
 *  提示
 */
@property(nonatomic,strong)MBProgressHUD *HUDforText;
/**
 *  选好的关系
 */
@property(nonatomic,copy)NSString * relationShipString;
/**
 *  关系数组
 */
@property(nonatomic,strong)NSArray * relationShipArray;

/**
 *  指向被选中的cell
 */
@property(nonatomic,strong)AddFamilyRemindCell *selectedCell;
/**
 *  获取点击的UIActionSheet点击的位置
 */
@property (nonatomic, assign) NSInteger actionSheetButtonIndex;
/**
 *  性别ActionSheet
 */
@property(nonatomic,strong)UIActionSheet *sexActionSheet;
/**
 *  头像ActionSheet
 */
@property(nonatomic,strong)UIActionSheet *headerActionSheet;
/**
 *  删除按钮--加载在table的footer上
 */
@property(nonatomic,strong)UIView * tabFooterDeleteView;
/**
 *  删除提示“确定删除吗”
 */
@property(nonatomic,strong)UIAlertView * deleteAlertView;

/**
 *  半透明的图片 -- 当点击升起pickerView的时候 这个也sheng起来
 */
@property(nonatomic,strong)UIView * alphaView;
/**
 * 对出生picker，和关系picker的是否是第一次创建做判断
 */
@property(nonatomic,assign)BOOL isFirst;

@end

@implementation EditMyFamilyDetialViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.isFirst = YES;
    self.view.backgroundColor = [UIColor whiteColor];
    [self makeNavBar];
    [self makeTableView];
    [self loadData];
}

/**
 *  设置导航条
 */
-(void)makeNavBar
{
    self.navigationItem.title = @"编辑家人信息";
    // 返回按钮图片
    UIBarButtonItem *backBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_返回.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backBtnClicked)];
    backBtnImg.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = backBtnImg;
    
    // 完成
    UIBarButtonItem *OkBtnImg = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"公用_完成.png"] style:UIBarButtonItemStylePlain target:self action:@selector(AFNetRequestForUpdateFamilyDetial:)];
    OkBtnImg.tintColor = [UIColor whiteColor];
    OkBtnImg.tag = 100;
    self.navigationItem.rightBarButtonItem = OkBtnImg;
}
/**
 *  返回--“用药提醒”
 */
-(void)backBtnClicked
{
    [self.navigationController popViewControllerAnimated:NO];
}


#pragma mark - AFNetUpdate--更新家人网络请求
/**
 *  更新家人信息数据
 */
-(void)AFNetRequestForUpdateFamilyDetial:(UIBarButtonItem *)itemButton
{
    
    //对参数进行合法判断
    if ([self.familyParameters[@"realname"] length] == 0) {

        [self showCustomHudSingleLine:@"真实姓名不可为空"];
        return;
    }
    if ([self.familyParameters[@"realname"] length] == 1) {
         [self showCustomHudSingleLine:@"真实姓名不可为1位"];
        return;
    }
    if ([self.familyParameters[@"realname"] length] > 10 ) {
        [self showCustomHudSingleLine:@"姓名长度不可大于10位"];
        return;
    }
    if ([self.familyParameters[@"username"] length] > 6) {
        [self showCustomHudSingleLine:@"昵称字数超过6位"];
        return ;
    }
    if ([self.familyParameters[@"username"] length] == 0) {
        [self showCustomHudSingleLine:@"昵称不能为空"];
        return ;
    }
    if ([self.familyParameters[@"mobile"] length] != 0) {
        if([CheckNumberClass checkPhoneNumber:[self.familyParameters objectForKey:@"mobile"]]==NO){
            return ;
        }
    }
    if ([self.familyParameters[@"idcard"] length] != 0) {
        if ([self.familyParameters[@"idcard"] length] == 18 || [self.familyParameters[@"idcard"] length] == 15) {
            
        }
        else{
            [self showCustomHudSingleLine:@"请输入正确的身份证号"];
            return ;
        }
    }
    [self showActionView];
    itemButton.enabled = NO;
    //参数初步判断合法后开始网络请求
    
    //1准备--可选参数
    NSMutableDictionary * updataParameters = [NSMutableDictionary dictionaryWithCapacity:0];
    //对 idcard，mobile，birthday这三个参数如果为空的话就不添加到上传网络的参数中去
    if ([self.familyParameters[@"idcard"] length] != 0) {
        [updataParameters setValue:self.familyParameters[@"idcard"] forKey:@"idcard"];
    }
    if ([self.familyParameters[@"mobile"] length] != 0) {
        [updataParameters setValue:self.familyParameters[@"mobile"] forKey:@"mobile"];
    }
    if ([self.familyParameters[@"birthday"] length]!= 0) {
        [updataParameters setValue:self.familyParameters[@"birthday"] forKey:@"birthday"];
    }
    
    if (self.familyParameters[@"gender"] != nil) {
        [updataParameters setValue:self.familyParameters[@"gender"] forKey:@"gender"];
    }
   
    //2 准备--必选参数
    [updataParameters setValue:self.familyParameters[@"fid"] forKey:@"fid"];
    [updataParameters setValue:self.familyParameters[@"username"] forKey:@"username"];
    [updataParameters setValue:self.familyParameters[@"realname"] forKey:@"realname"];
    [updataParameters setValue:self.familyParameters[@"type"] forKey:@"type"];
    [updataParameters setValue:kVersion forKey:@"version"];
    [updataParameters setValue:kPlatform forKey:@"platform"];

    //上传接口
    NSString *postURL = [NSString stringWithFormat:@"%@user/addhome/",kBaseURL];
    //上传图片
    NSData* imageData = UIImageJPEGRepresentation(self.familyHeaderImg,0.5);
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:postURL parameters:updataParameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        //判断是否选好了图片，如果没选就不走这个
        if (imageData) {
            [formData appendPartWithFileData:imageData name:@"file" fileName:@"familyHeaderImg.jpg" mimeType:@"image/jpeg"];
        }
    } error:nil];
    //
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSProgress *progress = nil;
    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        
        [self hiddenActionView];
        itemButton.enabled = YES;
        if (error)
        {
            MyNSLog("Error: %@", error);
        }else
        {
            //网络连接成功
            [self hiddenActionView];
            itemButton.enabled = YES;
            NSString *status=[NSString stringWithFormat:@"%@",[responseObject valueForKey:@"status"]];
            if ([status isEqualToString:@"0"])
            {
                MyNSLog("上传失败");
                [self showCustomHudSingleLine:responseObject[@"msg"]];
            }
            else
            {
                MyNSLog("成功");
                //获取家人fid
                NSDictionary * dic = responseObject[@"data"];
                MyNSLog("%@", dic);
                NSString * avatar = dic[@"avatar"];
                [updataParameters setValue:self.familyParameters[@"uid"] forKey:@"uid"];
                //头像
                [updataParameters setValue:avatar forKey:@"avatar"];
                [updataParameters setValue:self.familyParameters[@"idcard"] forKey:@"idcard"];
                [updataParameters setValue:self.familyParameters[@"mobile"] forKey:@"mobile"];
                [updataParameters setValue:self.familyParameters[@"birthday"] forKey:@"birthday"];
                //如果更新头像或者添加头像就把本地头像对应更新
                if (imageData) {
                    
                    //本地文件夹路径
                    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
                    //文件夹地址
                    NSString * headerImgFloder = [docPath stringByAppendingString:[NSString stringWithFormat:@"/FamilyHeaderFloder/"]];
                    //图片地址
                    NSString * newPicPath = [headerImgFloder stringByAppendingString:[NSString stringWithFormat:@"headerImg%@%@.jpg",self.familyAllDetialDic[@"uid"],self.familyAllDetialDic[@"fid"]]];
                    NSFileManager *fileManager = [NSFileManager defaultManager];
                    //如果这个文件夹存并且这个图片存在就进行下一步操作
                    if ([fileManager fileExistsAtPath:headerImgFloder] && [fileManager fileExistsAtPath:newPicPath]) {
                        
                        //把图片更新
                        [UIImageJPEGRepresentation(self.familyHeaderImg, 0.5) writeToFile:newPicPath atomically:YES];
                    }
                    else{
                        //这个文件夹不存在
                        if (![fileManager fileExistsAtPath:headerImgFloder]) {
                            //先创建文件夹
                            [[NSFileManager defaultManager] createDirectoryAtPath:headerImgFloder withIntermediateDirectories:YES attributes:nil error:nil];
                            //并且把创建这个文件夹的时间保存下来
                            NSUserDefaults * timeUser = [NSUserDefaults standardUserDefaults];
                            //先判断是否已经有了保存文件的时间
                            NSDate * oldTime = [timeUser objectForKey:@"FamilyHeaderFloderDate"];
                            NSDate * nowDate = [NSDate date];
                            //如果没有那么就把此时的时间保存下来
                            if (oldTime == nil) {
                                [timeUser setObject:nowDate forKey:@"FamilyHeaderFloderDate"];
                                [timeUser synchronize];
                            }
                        }
                       
                        //再 -- 把图片更新
                        [UIImageJPEGRepresentation(self.familyHeaderImg, 0.5) writeToFile:newPicPath atomically:YES];
                    }
                }
                
                [self.delegate reloadShowFamilyDetialWithFamilyDic:updataParameters];
                //pop回去到展示页面
                [self.navigationController popViewControllerAnimated:NO];

            }
        }
  
    }];
    [uploadTask resume];
}

#pragma mark - AFNetDelete--删除家人
//删除家人之后返回列表页面
-(void)AFNetRequestForDeleteTheFamily
{
    [self showActionView];
    
    NSString *postURL = [NSString stringWithFormat:@"%@user/deletehome/",kBaseURL];
    NSDictionary * deleteParameters = @{@"platform":kPlatform,@"version":kVersion,@"fid":self.familyParameters[@"fid"]};
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:postURL parameters:deleteParameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self hiddenActionView];
        MyNSLog("网络请求成功");
        NSNumber * statusNum = [responseObject objectForKey:@"status"];
        NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
        NSString * statusString = [numberFormatter stringFromNumber:statusNum];
        if ([statusString isEqualToString:@"0"]) {
            alertContent([responseObject objectForKey:@"msg"]);
            MyNSLog("删除失败");
        }else
        {
            MyNSLog("%@", responseObject[@"msg"]);
            //把家人的头像图片删除--先判断家人有无头像
            NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            //文件夹地址
            NSString * headerImgFloder = [docPath stringByAppendingString:[NSString stringWithFormat:@"/FamilyHeaderFloder/"]];
            //图片地址
            NSString * newPicPath = [headerImgFloder stringByAppendingString:[NSString stringWithFormat:@"headerImg%@%@.jpg",self.familyAllDetialDic[@"uid"],self.familyAllDetialDic[@"fid"]]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //如果这个文件夹存并且这个图片存在就进行下一步操作
            if ([fileManager fileExistsAtPath:headerImgFloder] && [fileManager fileExistsAtPath:newPicPath]) {
                //然后删除
                [[NSFileManager defaultManager] removeItemAtPath:newPicPath error:nil];
            }
            
            if (self.isPresent) {
                
                [self dismissViewControllerAnimated:YES completion:nil];
                
            }else{
                //删除成功后--返回到列表页面
                
                //我的家人蜂窝页面过来的返回到我的家人蜂窝页面
                if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-4] isKindOfClass:[MyFamilyViewController class]]) {
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-4] animated:YES];
                }
                //从用提醒过来--返回用药提醒
                else if ([[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-4] isKindOfClass:[TakeDrugsViewController class]]) {
                    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count-4] animated:YES];
                }
            
            }
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        MyNSLog("删除家人网络--失败");
        [self hiddenActionView];
    }];

}

#pragma mark - 加载数据
-(void)loadData
{

    self.familyAllDetialDic = [self.familyArray firstObject];
    //把展示页面传过来的家人显示信息传给参数字典
    self.familyParameters = [NSMutableDictionary dictionaryWithCapacity:0];
    [self.familyParameters setDictionary:self.familyAllDetialDic];
    
    
    self.relationShipArray = @[@"祖父母", @"父母",@"其他平辈", @"子女", @"孙辈",@"爱人"];
    //必填--提示
    self.requiredRemiderArray = @[@"真实姓名",@"关       系",@"昵       称"];
    //必填--内容
    self.requiredValueArray = @[self.familyAllDetialDic[@"realname"],[self.relationShipArray objectAtIndex:[self.familyAllDetialDic[@"type"] intValue]-1],self.familyAllDetialDic[@"username"]];
    //选填内容-1
    self.optionRemindFirstArray = @[@"性       别",@"出生年月"];
    NSArray * genderArray = @[@"",@"男",@"女"];
    
    self.optionValueFirstArray = @[[genderArray objectAtIndex:[self.familyAllDetialDic[@"gender"] intValue]],self.familyAllDetialDic[@"birthday"]];
    
    //选填内容-2
    self.optionReminderSecondArray = @[@"手  机  号",@"身  份  证"];
    self.optionValueSecondArray = @[self.familyAllDetialDic[@"mobile"],self.familyAllDetialDic[@"idcard"]];
    
    self.tempDic = @{@"真实姓名":@"realname",@"关       系":@"type",@"昵       称":@"username",@"性       别":@"gender",@"出生年月":@"birthday",@"手  机  号":@"mobile",@"身  份  证":@"idcard"};
   
    self.placeholedeDic = @{@"真实姓名":@"请输入对方的真实姓名(最多10位)",@"手  机  号":@"请输入对方的手机号码",@"身  份  证":@"请输入对方身份证",@"昵       称":@"请输入对方的昵称/详细关系(最多6位)"};
    
}

#pragma mark - 创建tableView
-(void)makeTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //隐藏横向和竖向的滑条
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.tableView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.view addSubview:self.tableView];
    //加载tab的footerview---触发删除家人提示
    [self createDeleteButtonForTableFooterView];
   
    
}
#pragma mark --“删除”footerView---删除这个家人
-(void)createDeleteButtonForTableFooterView
{
    self.tabFooterDeleteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 64)];
    if (IPhone6Plus) {
        self.tabFooterDeleteView.height = 90;
    }
    self.tableView.tableFooterView = self.tabFooterDeleteView;
    CGFloat btnLeft = 15;
    CGFloat btnHeight = 44;
    CGFloat textfont = 13;
    if (IPhone6Plus) {
        btnLeft = 20;
        btnHeight = 53;
        textfont = 15;        
    }
    
    UIButton * deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(btnLeft, 10, kScreenWidth-2*btnLeft, btnHeight);
    if (IPhone6Plus) {
        deleteBtn.top = 20;
    }
    [self.tabFooterDeleteView addSubview:deleteBtn];
    deleteBtn.backgroundColor = [UIColor colorWithRed:35/255.0 green:205/255.0 blue:235/255.0 alpha:1];
    [deleteBtn setTitle:@"删除家人" forState:UIControlStateNormal];
    [deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    deleteBtn.titleLabel.font = [UIFont systemFontOfSize:textfont];
    [deleteBtn addTarget:self action:@selector(deleteTheFamilyDown) forControlEvents:UIControlEventTouchUpInside];
    self.deleteAlertView = [[UIAlertView alloc] initWithTitle:@"确定要删除家人吗？" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];

}
//
-(void)deleteTheFamilyDown
{
    [self.deleteAlertView show];//弹出提示
    //"确定"
// - --性别选中提示----“删除”家人确定提示

}

#pragma mark - tableView的代理方法
//多少段
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;

}
//各段有多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 3;
    }else
    {
        return 2;
    }
}
//段头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        if (IPhone6Plus) {
            return 12;
        }else{
            return 10;
        }
    }else if (section == 1 || section == 2){
        if (IPhone6Plus) {
            return 30;
        }else{
            return 20;
        }
       
    }else
    {
        return 0.01;
    }
}
//给1段“必填内容”和2段“选填内容”添加段头
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    CGFloat viewHeight = 20;
    CGFloat viewLeft = 15;
    CGFloat textfont = 13;
    if (IPhone6Plus) {
        viewHeight = 30;
        viewLeft = 20;
        textfont = 15;
    }
    
    if (section == 1) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewHeight)];
        UILabel *requiredLable = [[UILabel alloc] initWithFrame:CGRectMake(viewLeft, 0, kScreenWidth-viewLeft, viewHeight)];
        view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        requiredLable.text = @"必填内容";
        requiredLable.textAlignment = NSTextAlignmentLeft;
        requiredLable.font = [UIFont systemFontOfSize:textfont];
        requiredLable.textColor = [UIColor grayColor];
        [view addSubview:requiredLable];
        return view;
    }else if(section == 2)
    {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, viewHeight)];
        UILabel *optionLable = [[UILabel alloc] initWithFrame:CGRectMake(viewLeft, 0, kScreenWidth-viewLeft, viewHeight)];
        optionLable.text = @"选填内容";
        optionLable.textAlignment = NSTextAlignmentLeft;
        optionLable.font = [UIFont systemFontOfSize:textfont];
        optionLable.textColor = [UIColor grayColor];
        view.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
        [view addSubview:optionLable];

        return view;
    }else
    {
        return nil;
    }


}


//段尾高
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
//各行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (IPhone6Plus) {
            return 78;
        }else{
            return 64;
        }
    }else
    {
        if (IPhone6Plus) {
            return 53;
        }else{
            return 44;
        }
    }
}
#pragma mark -- cell--加载
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)//第0段--编辑头像
    {
        FamilyInfoFirstSectionCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Header"];
        if (cell == nil) {
            if (IPhone6Plus) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"FamilyInfoFirstSectionCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"FamilyInfoFirstSectionCell" owner:self options:nil] firstObject];
            }
        }
        cell.familyHeaderImgView.clipsToBounds = YES;
        cell.familyHeaderImgView.layer.cornerRadius = 3;
        
        if (indexPath.row == 0) {
            
            cell.topLineView.backgroundColor = cellLineColor;
            cell.topLineView.height = 0.5;
            cell.topLineView.width = kScreenWidth;
            cell.bottomLineView.backgroundColor = cellLineColor;
            cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
            
            //本地文件夹路径
            NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
            //文件夹地址
            NSString * headerImgFloder = [docPath stringByAppendingString:[NSString stringWithFormat:@"/FamilyHeaderFloder/"]];
            //图片地址
            NSString * newPicPath = [headerImgFloder stringByAppendingString:[NSString stringWithFormat:@"headerImg%@%@.jpg",self.familyAllDetialDic[@"uid"],self.familyAllDetialDic[@"fid"]]];
            NSFileManager *fileManager = [NSFileManager defaultManager];
            //如果这个文件夹存并且这个图片存在就进行下一步操作
            if ([fileManager fileExistsAtPath:headerImgFloder] && [fileManager fileExistsAtPath:newPicPath]) {
                UIImage * img = [UIImage imageWithContentsOfFile:newPicPath];
                if (img != nil) {
                    [cell.familyHeaderImgView setImage:img];
                }else{
                    [cell.familyHeaderImgView setImageWithURL:[NSURL URLWithString:self.familyAllDetialDic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
                }
                
            }else{
                [cell.familyHeaderImgView setImageWithURL:[NSURL URLWithString:self.familyAllDetialDic[@"avatar"]] placeholderImage:[UIImage imageNamed:@"默认头像"]];
            }
            
            
            cell.familyNameLable.hidden = YES;
            cell.familyHeaderImgView.tag = 1990;
            cell.touchAddHeaderLable.text = @"点击上传家人头像";
            [cell.jumpImgView setImage:[UIImage imageNamed:@"公用_跳转.png"]];
           
            cell.addImgButton.tag = 1989;
            cell.addImgButton.width = kScreenWidth;
            [cell.addImgButton addTarget:self action:@selector(changeHeaderImgView:) forControlEvents:UIControlEventTouchUpInside];
            cell.jumpImgView.right = kScreenWidth-15;
            cell.touchAddHeaderLable.right = cell.jumpImgView.left-3;
            
            return cell;
        }
        else{
            return nil;
        }
        
    }
    else
    {
        AddFamilyRemindCell * cell = [tableView dequeueReusableCellWithIdentifier:@"ID"];
        if (cell == nil) {
            if (IPhone6Plus) {
                 cell = [[[NSBundle mainBundle] loadNibNamed:@"AddFamilyRemindCell" owner:self options:nil] lastObject];
            }else{
                cell = [[[NSBundle mainBundle] loadNibNamed:@"AddFamilyRemindCell" owner:self options:nil] firstObject];
            }
        }
        [cell.jumpImgView setImage:[UIImage imageNamed:@"公用_跳转.png"]];
        cell.jumpImgView.right = kScreenWidth-15;
        cell.getInformationLable.frame = CGRectMake(cell.familyReminderLable.right+10, cell.getInformationLable.top, cell.jumpImgView.left -cell.familyReminderLable.right-10 - 3  , cell.getInformationLable.height);
        cell.getInformationLable.right = cell.jumpImgView.left-3;
        
        if (indexPath.section == 1)//第一段:必填内容
        {
            cell.familyReminderLable.text = self.requiredRemiderArray[indexPath.row];
            cell.getInformationLable.text = self.requiredValueArray[indexPath.row];
            cell.topLineView.backgroundColor = cellLineColor;
            cell.topLineView.height = 0.5;
            cell.topLineView.width = kScreenWidth;
            if (indexPath.row == 1) {
               
                cell.topLineView.frame = CGRectMake(15, 0, kScreenWidth-15, 0.5);
                if (IPhone6Plus) {
                    cell.topLineView.left = 20;
                }
            }
            //选填内容
            if (indexPath.row == 2) {
                cell.topLineView.frame = CGRectMake(15, 0, kScreenWidth-15, 0.5);
                if (IPhone6Plus) {
                    cell.topLineView.left = 20;
                }
                cell.bottomLineView.backgroundColor = cellLineColor;
                cell.bottomLineView.frame = CGRectMake(0, cell.height-0.5, kScreenWidth, 0.5);
            }
                        
        }
        if (indexPath.section == 2) {
            cell.familyReminderLable.text = self.optionRemindFirstArray[indexPath.row];
            cell.getInformationLable.text = self.optionValueFirstArray[indexPath.row];
            if (indexPath.row == 0) {
                cell.topLineView.backgroundColor = cellLineColor;
                cell.topLineView.height = 0.5;
                cell.topLineView.width = kScreenWidth;
            }
            if (indexPath.row == 1) {
                cell.topLineView.backgroundColor = cellLineColor;
                cell.topLineView.frame = CGRectMake(15, 0, kScreenWidth-15, 0.5);
                if (IPhone6Plus) {
                    cell.topLineView.left = 20;
                }
                cell.bottomLineView.backgroundColor = cellLineColor;
                cell.bottomLineView.frame = CGRectMake(15, cell.height-0.5, kScreenWidth-15, 0.5);
                if (IPhone6Plus) {
                    cell.bottomLineView.left = 20;
                }
            }
        }
        if (indexPath.section == 3) {
            cell.familyReminderLable.text = self.optionReminderSecondArray[indexPath.row];
            cell.getInformationLable.text = self.optionValueSecondArray[indexPath.row];
            if (indexPath.row == 1) {
                cell.topLineView.backgroundColor = cellLineColor;
                cell.topLineView.frame = CGRectMake(15, 0, kScreenWidth-15, 0.5);
                if (IPhone6Plus) {
                    cell.topLineView.left = 20;
                }
                cell.bottomLineView.backgroundColor = cellLineColor;
                cell.bottomLineView.frame = CGRectMake(0,cell.height-0.5, kScreenWidth, 0.5);
            }
            
        }
        
        return cell;
    
    }

}
#pragma mark - 选中某一个cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isFirst) {
        [self.myDatePickerView removeFromSuperview];
        [self.relationShipView removeFromSuperview];
        [self makeBirthdayPickerView];
        [self makeRelationShipPickerView];
        self.isFirst = NO;
    }
        
    if (indexPath.section != 0)//除了第0段
    {
        self.selectedCell = (AddFamilyRemindCell *)[self.tableView cellForRowAtIndexPath:indexPath];
        //切割字符串--把空格切割掉
        NSArray * titleArray  = [self.selectedCell.familyReminderLable.text componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" "]];
        /**
         *  切割完成后的字符串
         */
        NSMutableString *titleString = [NSMutableString stringWithCapacity:0];
        for (NSString *str in titleArray) {
            [titleString appendString:str];
        }
        //点击--关系
        if ([titleString isEqualToString:@"关系"])
        {
            //滑动table使最后一个cell漏出来
            [self scrollToRowAtLastSecionWithLastIndexPath];
            [self makeAlphaView];
            [self.view bringSubviewToFront:self.relationShipView];
            //点击“关系”弹出 关系选择器pickerview
            [UIView animateWithDuration:0.35 animations:^{
                self.relationShipView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
                self.alphaView.alpha = 0.35;
            } completion:^(BOOL finished) {
                
            }];
        }
        //点击--性别
        else if ([titleString isEqualToString:@"性别"])
        {
            if (self.selectedCell.getInformationLable.text.length != 0 ) {
                return;
            }else{
                [self addSexActionSheet];
            }
        }
        //点击--“出生年月”
        else if ([titleString isEqualToString:@"出生年月"])
        {
            //滑动table使最后一个cell漏出来
            [self scrollToRowAtLastSecionWithLastIndexPath];
            [self makeAlphaView];
            [self.view bringSubviewToFront:self.myDatePickerView];
            //点击“出生年月”让年月选择器上来
            [UIView animateWithDuration:0.35 animations:^{
                
                self.myDatePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin-216, kScreenWidth, 216);
                //iphone4\4s
                if (kScreenHeight == 480) {
                    //把table也向上移动，是该cell并不被覆盖
                    self.tableView.frame = CGRectMake(0, -128, kScreenWidth, kScreenHeight-iOS7TopMargin);
                }
                //iphone5以上
                if (kScreenHeight == 568) {
                    self.tableView.frame = CGRectMake(0, -45, kScreenWidth, kScreenHeight-iOS7TopMargin);
                }
                
                self.alphaView.alpha = 0.35;
            } completion:^(BOOL finished) {
                
            }];
            
        }
        //点击--其他行
        else
        {
            WriteFamilyViewController *write = [[WriteFamilyViewController alloc] init];
            write.textFieldPlaceholder = [self.placeholedeDic objectForKey:self.selectedCell.familyReminderLable.text];
            write.delegate = self;
            write.navBarTitle = titleString;
            write.textString = self.selectedCell.getInformationLable.text;
            [self.navigationController pushViewController:write animated:YES];
        }
    }
    
}
#pragma mark - WriteFamilyViewControllerDelegate的代理方法

-(void)reloadTableViewSelectedCellPlaceholeder:(NSString *)placeholder
{
    self.selectedCell.getInformationLable.text = placeholder;
    NSString * parKey = [self.tempDic objectForKey:self.selectedCell.familyReminderLable.text];
    //把传过来的值存入参数字典
    [self.familyParameters setValue:placeholder forKey:parKey];
    MyNSLog("%@", self.familyParameters);
}

#pragma mark - "出生年月"选择器
/**
 *  创建生日选择器
 */
-(void)makeBirthdayPickerView
{
    self.myDatePickerView = [[MyDatePickerView alloc] initWithFrame:CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216)];
    [self.view addSubview:self.myDatePickerView];
    self.myDatePickerView.backgroundColor = [ClassMethodsViewController colorWithHexString:BACK_BACKGROUNDCOLOR_16];
    [self.myDatePickerView.cancleButton addTarget:self action:@selector(birthDateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.myDatePickerView.cancleButton.tag = 1000;
    [self.myDatePickerView.sureButton addTarget:self action:@selector(birthDateButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.myDatePickerView.sureButton.tag = 1001;
    
}

/**
 *  取消  确定  按钮触发的事件
 *
 *  @param button 按钮的tag值1000是“取消”，1001是“确定”
 */
-(void)birthDateButtonClicked:(UIButton*)button
{
    switch (button.tag) {
        case 1000:
        {
            [self recoverPickerViewAndTableViewFrame];
        }
            break;
        case 1001:
        {
            self.selectedCell.getInformationLable.text = [self.myDatePickerView getDateString];
            [self.familyParameters setValue:[self.myDatePickerView getDateString] forKey:@"birthday"];
            [self recoverPickerViewAndTableViewFrame];
        }
            break;
            
        default:
            break;
    }
    
    
}

#pragma mark - "关系"选择器
/**
 *  创建关系选择器
 */
-(void)makeRelationShipPickerView
{
    
    self.relationShipView = [[[NSBundle mainBundle] loadNibNamed:@"FamilyRelationshipPickerView" owner:self options:nil] lastObject];
    self.relationShipView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 216);
    [self.view addSubview:self.relationShipView];
    /**
     *  pickerView--关系选择器
     */
    self.relationShipView.relationPickerView.delegate = self;
    self.relationShipView.relationPickerView.dataSource = self;
    self.relationShipView.relationPickerView.backgroundColor = [UIColor whiteColor];
    self.relationShipView.relationPickerView.showsSelectionIndicator=YES;
    /**
     *  初始选择第3行--“其他平辈”
     */
    [self.relationShipView.relationPickerView selectRow:2 inComponent:0 animated:NO];
    /**
     *  把初始选择的“其他平辈”参数值 4
     */
    self.relationShipString =[NSString stringWithFormat:@"%d",3+1];
    //“取消”--“确定”
    [self.relationShipView.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    self.relationShipView.cancleButton.tag = 2000;
    [self.relationShipView.cancleButton addTarget:self action:@selector(relationShipButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.relationShipView.sureButton setTitle:@"确定" forState:UIControlStateNormal];
    self.relationShipView.sureButton.tag = 2001;
    [self.relationShipView.sureButton addTarget:self action:@selector(relationShipButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
/**
 *  关系选择器“取消”，“确定” 按钮的触发事件
 *
 *  @param button 按钮tag值2000是“取消”，2001是“确定”
 */
-(void)relationShipButtonClicked:(UIButton*)button
{
    //“取消”
    if (button.tag == 2000) {
        
    }
    //"确定"
    if (button.tag == 2001) {

        MyNSLog("%d,%@",[self.relationShipString intValue],[self.relationShipArray objectAtIndex:[self.relationShipString intValue]-1]);
        self.selectedCell.getInformationLable.text = [self.relationShipArray objectAtIndex:[self.relationShipString intValue]-1];
        
        //给参数字典设置value和key(原来有就是修改，原来没有就是添加)
        [self.familyParameters setValue:self.relationShipString forKey:@"type"];
        
    }
    //点“取消”/“确定”--操作完之后都让键盘恢复
    [self recoverPickerViewAndTableViewFrame];
}
#pragma mark - 关系pickerView的代理方法
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return 1;
    }
    else
    {
        return 0;
    }
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return self.relationShipArray.count;
    }else
    {
        return 0;
    }
}
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([pickerView isEqual:self.relationShipView.relationPickerView]) {
        return self.relationShipArray[row];
    }else
    {
        return nil;
    }
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (pickerView == self.relationShipView.relationPickerView) {
        self.relationShipString = [NSString stringWithFormat:@"%ld",row+1];
        MyNSLog("%@",self.relationShipString);
    }
    
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    if (pickerView == self.relationShipView.relationPickerView) {
        return 40;
    }else
    {
        return 0;
    }
}
#pragma mark - 触发--添加头像
-(void)changeHeaderImgView:(UIButton*)button
{
    [self recoverPickerViewAndTableViewFrame];
    MyNSLog("点击上传家人头像");
    self.headerActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"照相机",@"图片库", nil];
    [self.headerActionSheet showInView: [[UIApplication sharedApplication].delegate window]];
    

    
}
#pragma mark - 获取头像的代理方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    
     UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
     [picker dismissViewControllerAnimated:YES completion:^{
     
         self.familyHeaderImg = image;
         UIImageView * cellHeaderImgView = (UIImageView *)[self.view viewWithTag:1990];
         [cellHeaderImgView setImage:self.familyHeaderImg];
     }];
    
}

#pragma mark - 触发选择性别
-(void)addSexActionSheet{
    self.sexActionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate: self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
    [self.sexActionSheet showInView: [[UIApplication sharedApplication].delegate window]];
}
#pragma mark - -ActionSheet的代理方法
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //性别 提醒
    if (actionSheet == self.sexActionSheet) {
        if (buttonIndex != 2) {
            
            self.actionSheetButtonIndex = buttonIndex;
            UIAlertView *sexAlertView = [[UIAlertView alloc] initWithTitle:@"性别的选取" message:@"确定后不可修改" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            sexAlertView.tag = 1417;
            [sexAlertView show];
        }
    }
    //头像 提醒
    if (actionSheet == self.headerActionSheet) {
        //照相机
        if (buttonIndex == 0)
        {
            AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStatus != AVAuthorizationStatusAuthorized)
            {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"相机被禁用" message:@"请在iPhone的“设置-隐私-相机”中允许安好访问您的相机。" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }
            else
            {
                
                if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                    UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                    pickerImage.delegate=self;
                    pickerImage.allowsEditing=YES;
                    //pickerImage.mediaTypes              默认是静态图片，指定摄像头获取获取数据类型
                    pickerImage.sourceType=UIImagePickerControllerSourceTypeCamera;//指定使用相机
                    [self presentViewController:pickerImage animated:YES completion:nil];
                }else{
                    
                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"没有摄像头或摄像头损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                    [alert show];
                }
            }
            
        }
        //图片库
        else if (buttonIndex == 1)
        {
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
                UIImagePickerController *pickerImage=[[UIImagePickerController alloc] init];
                pickerImage.delegate=self;
                NSArray * array1=[NSArray arrayWithObjects:(NSString *)kUTTypeImage,(NSString*)kUTTypeMovie, nil];
                pickerImage.mediaTypes=array1;
                pickerImage.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
                pickerImage.allowsEditing=YES;
                [self presentViewController:pickerImage animated:YES completion:nil];
            }
            else
            {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"警告" message:@"照片库不存在或已损坏" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
            }
        }
    }
}
#pragma mark - AlertView--性别选中提示----“删除”家人确定提示
//性别alert提醒---AND---删除alert提醒
- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    //提醒是否确定要删除家人--确定就走下面的方法
    if (alertView == self.deleteAlertView)
    {
        if (alertView == self.deleteAlertView) {
            if (buttonIndex == 0)//确定
            {
                //删除
                [self AFNetRequestForDeleteTheFamily];
            }
        }
    }
    //提醒--选中性别之后就不可改变
    if (alertView.tag == 1417) {
        if (buttonIndex==1) {
            if (self.actionSheetButtonIndex == 0) {
                self.selectedCell.getInformationLable.text = @"男";
                [self.familyParameters setValue:@"1" forKey:@"gender"];
            }else if (self.actionSheetButtonIndex == 1){
                self.selectedCell.getInformationLable.text = @"女";
                [self.familyParameters setValue:@"2" forKey:@"gender"];
            }
        }
    }
}


#pragma mark - pickerView下落，tableview复原
-(void)recoverPickerViewAndTableViewFrame
{
    [UIView animateWithDuration:0.35 animations:^{
        self.relationShipView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.myDatePickerView.frame = CGRectMake(0, kScreenHeight-iOS7TopMargin, kScreenWidth, 216);
        self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-iOS7TopMargin);
        self.alphaView.alpha = 0;
    } completion:^(BOOL finished) {
    }];
}
#pragma mark - 让tableview的最后一行cell显示出来
-(void)scrollToRowAtLastSecionWithLastIndexPath
{
    //找到最后一个cell
    NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:1 inSection:3];//制定第3段的坐标为1的cell->indexPath
    //让屏幕上滑到指定的一个cell完全显示出来
    [self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark - 创建半透明的view
-(void)makeAlphaView
{
    self.alphaView = [[UIView alloc] initWithFrame:CGRectMake(0,0, kScreenWidth, kScreenHeight-iOS7TopMargin)];
    self.alphaView.backgroundColor = [UIColor blackColor];
    self.alphaView.alpha = 0;
    [self.view addSubview:self.alphaView];
    //给这个半透明的View添加一个手势
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(alphaViewTapClicked:)];
    [self.alphaView addGestureRecognizer:tap];
}
-(void)alphaViewTapClicked:(UITapGestureRecognizer*)tap{
    
    [self recoverPickerViewAndTableViewFrame];
}

@end
